class User < ActiveRecord::Base
  
  has_many :user_book
  
  attr_accessible :login, :mail, :mail_notification, :salt, :password, :password_confirmation
  attr_accessor :password
  attr_protected :admin, :as => :admin

  validates_presence_of :login, :length => { :minimum => 5 }
  validates_confirmation_of :password
  validates_presence_of :password, :on => :create, :length => { :minimum => 8 }, :on => :create
  validates :mail, :presence => true
  validates_uniqueness_of :mail, :login
  before_save :encrypt_password
  

  def self.authenticate(login, password)
    user = find_by_login(login)

    if user && user.password == BCrypt::Engine.hash_secret(password, user.salt)
      user
    else
      nil
    end
  end
  
  def encrypt_password
    if password.present?
      self.salt = BCrypt::Engine.generate_salt
      self.password = BCrypt::Engine.hash_secret(password, salt)
    end
  end
  
  def to_s
    "#{self.id}.#{self.login}"
  end
  
  def password()
    read_attribute(:password)
  # self[:attribute]
  end
  
  def password=(password)
    write_attribute(:password, password)
  # self[:password]=password
  end

  
end
